<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Interfaces\ApiInterface;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Yiqida extends AbstractApi
{
    /**
     * 签名
     *
     * @param string $json 请求数据转json
     * @param string $key 密钥
     * @param string $time 时间
     * @return string
     */
    public function sign(string $json ,string $key,string $time): string
    {
        return md5($time . $json .$key );
    }

    /**
     * 获取请求url
     *
     * @param string $url 路径
     * @param string $timestamp  时间戳
     * @param string $sign 签名
     * @return string
     */
    public function url(string $url, string $sign,string $user,string $timestamp): string
    {
        return sprintf(
            '%s?timestamp=%s&userName=%s&sign=%s',
            $url,
            $timestamp,
            $user,
            $sign
        );
    }

    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        $time = millisecondTimestamp();
        return $this->httpClient($http)->asJson()->post($this->url($config->recharge_url,$this->sign(json_encode($this->rechargeData($bean)),$bean->getSecretKey(),$time),$bean->getSupplierNum(),$time), $this->rechargeData($bean));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        return [
            'commodityId'       => $bean->getGoodsId(), //商品编号id
            'external_orderno'   => $bean->getOrderNo(), //订单号
            'buyCount'      => $bean->getRechargeNum(), //充值数量
            'remark'=>'',
            'callbackUrl'     => $bean->getNotifyUrl(), //异步回调地址
            'externalSellPrice'     => $bean->getUnitPrice(), //商品的单价
            'template'      => [urlencode($bean->getAccount())], //要充值的用户
        ];

    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('externalOrderno', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(true)->setRechargeSuccess($status == 4);
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $time = millisecondTimestamp();
        $res =  httpClient()->post($this->url($config->balance_url,$this->sign(json_encode([]),$bean->getSecretKey(),$time),$bean->getSupplierNum(),$time), $data =[]);
        return data_get(json2array($res->body()), $config->balance_title, 0);
    }

    public function goods(InterfaceConfiguration $config, BasicInformation $bean): array|string
    {
        $time = millisecondTimestamp();
        $data = [
            'id' => $bean->getGoodsId(), //商品编码
        ];
        $response =  httpClient()->post($this->url($config->good_url,$this->sign(json_encode($data),$bean->getSecretKey(),$time),$bean->getSupplierNum(),$time), $data)->json();
        if (empty($response['data'])){
            return '未找到商品信息';
        }else{
            return [
                'goods_code'=>$bean->getGoodsId(),//第三方编码
                'goods_belong'=>$config->id,
                'goods_name'=>$response['data']['name'],
                'unit_price'=>$response['data']['price'],
                'time'=>date('Y-m-d H:i:s'),
                'goods_type'=>1,
            ];
        }
    }
}
